package com.af.security.mgt.account.register.token.event;

import com.af.security.mgt.account.register.log.UserRegisterLog;
import com.af.security.mgt.account.register.log.UserRegisterLogService;
import com.af.security.mgt.account.register.token.UserRegisterTokenService;
import com.af.security.mgt.user.User;
import com.af.service.AfI18nService;
import org.hibernate.JDBCException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Component;

/**
 * @author : zhenyun.su
 * @since : 2020/09/04
 */

@Component
public class UserRegisterTokenListener implements ApplicationListener<UserRegisterTokenEvent> {
    private static final Logger logger = LoggerFactory.getLogger(UserRegisterTokenListener.class);

    @Autowired
    private UserRegisterLogService registerLogService;
    @Autowired
    private UserRegisterTokenService registerTokenService;

    @Autowired
    private AfI18nService i18nService;

    @Override
    public void onApplicationEvent(UserRegisterTokenEvent event) {
        logger.debug("onApplicationEvent, the RegisterConfirmEvent is triggered to send an email to confirm the registration.");
        UserRegisterLog registerLog = UserRegisterLog.of(event.getUser().getId(), "" ,"");
        String errorMessage = null;
        try {
            User user = event.getUser();
            String subject = i18nService.getI18n("register.mail.confirm.Subject", null, event.getLocale());
            String message = i18nService.getI18n("register.mail.confirm.context", null, event.getLocale());
            String text = message + " \n " + event.getAppUrl();
            registerLog.setSubject(subject);
            registerLog.setText(text);

            String token = registerTokenService.sendTokenMail(user, subject, text);
            registerLog.setToken(token);
            registerLog.setStatus(true);
        } catch (MailException me) {
            errorMessage = "Mail sending error: " + me.getMessage();
        } catch (JDBCException je) {
            errorMessage = "Database operation error: " + je.getMessage();
        } catch (Exception e) {
            errorMessage = "Internal server error: " + e.getMessage();
        } finally {
            if (errorMessage != null) {
                logger.error(errorMessage);
                registerLog.setStatus(false);
                registerLog.setLastMsg(errorMessage);
            } else {
                registerLog.setLastMsg("success");
            }
            registerLogService.saveLog(registerLog);
        }
    }
}
